import router from "@/router";
import type {
  NavigationGuardNext,
  RouteLocationNormalized,
  RouteRecordRaw,
} from "vue-router";
import { useUserStore } from "@/pinia/user";
import { storeToRefs } from "pinia";
import { useMenuStore } from "@/pinia/menu";
import { ENotice, showFullLoading, hideFullLoading } from "@/utils/tool";
import { el } from "element-plus/es/locale";

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  showFullLoading();

  const userStore = useUserStore();
  const token = userStore.token;

  if (token) {
    // 防止重复登录
    if (to.path == "/login") {
      ENotice("已登录", "success");
      console.log("已登录，跳转首页");
      // return next({ path: from.path ? from.path : "/home" });
      return next({ path: "/home" });
    }

    // 已经登录
    const menuStore = useMenuStore();
    // 判断路由是否加载完成
    if (!menuStore.loadRoutesFlag) {
      try {
        // 请求生成动态路由
        const dynamicRoutes = await menuStore.generateRoutes();
        dynamicRoutes.forEach((route: RouteRecordRaw) =>
          router.addRoute(route)
        );
        console.log("请求生成动态路由");
        next({ ...to, replace: true });
      } catch (error) {
        console.error(error);
        // 路由加载失败，重置 token 并重定向到登录页
        await userStore.clearUserData();
        next({ path: "/login" });
      }
    }

    // 处于登录中，则请求用户信息
    if (token && !userStore.userInfo) {
      try {
        await userStore.GetUserInfo();
        console.log("处于登录中");
        next({ ...to, replace: true });
      } catch (error) {
        console.error(error);
        // 获取用户信息失败，重置 token 并重定向到登录页
        await userStore.clearUserData();
        next({ path: "/login" });
      }
    }

    let title = (to.meta.title ? to.meta.title : "") + "-后台";
    document.title = title;
    next();
  } else {
    if (to.path !== "/login") {
      // 没有登录，跳转到登录页
      ENotice("请先登录", "error");
      // console.log("没有登录，跳转到登录页");
      return next({ path: "/login", query: { redirect: to.path } });
    } else {
      console.log("登录中");
      next()
    }
  }
  // if (to.name === "destructuring") {
  //   // next(false) 以取消导航
  //   next(false)
  // } else{
  //     next()
  // }
  // return next({ path: "/home" });
});

// 重定向到登录页
function redirectToLogin(
  to: RouteLocationNormalized,
  next: NavigationGuardNext
) {
  const params = new URLSearchParams(to.query as Record<string, string>);
  const queryString = params.toString();
  const redirect = queryString ? `${to.path}?${queryString}` : to.path;
  next(`/login?redirect=${encodeURIComponent(redirect)}`);
}

// 全局后置守卫
router.afterEach(() => hideFullLoading());
